package com.example.projectmanagement.config;

import com.example.projectmanagement.exception.SensitiveXssContentException;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * XSS防护过滤器
 *
 * 文件上传不能用这个，会改变 multipart结构，导致后面解析不到
 */
public class XssFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // Skip XSS filtering for video upload endpoint to avoid multipart form data issues
        String requestURI = httpRequest.getRequestURI();
        if (requestURI != null && requestURI.contains("/api/study/videos/upload")) {
            chain.doFilter(request, response);
            return;
        }
        
        try {
            XssHttpServletRequestWrapper wrappedRequest = new XssHttpServletRequestWrapper(httpRequest);
            chain.doFilter(wrappedRequest, response);
        } catch (SensitiveXssContentException e) {
            // 设置响应状态码和内容类型
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.setContentType("application/json;charset=UTF-8");
            
            // 返回错误信息
            String jsonResponse = "{\"error\":\"" + e.getMessage() + "\"}";
            httpResponse.getWriter().write(jsonResponse);
        }
    }
}